package moxl.relaxng.schema;

import moxl.dom.MoxlAttribute;
import moxl.dom.DefaultQualifiedName;
import moxl.dom.DefaultXmlNamespace;
import moxl.dom.MoxlElement;
import moxl.dom.QualifiedName;
import moxl.dom.XmlNamespace;
import moxl.relaxng.schema.nameclasses.Name;
import moxl.relaxng.schema.patterns.ChoicePattern;
import moxl.relaxng.schema.patterns.ElementPattern;
import moxl.relaxng.schema.patterns.EmptyPattern;

public class PatternFactory
{
	public Pattern createPattern(MoxlElement patternDefinitionElement)
	{
		QualifiedName patternName = patternDefinitionElement.getName();
		if (patternName.equals(RelaxNgSchemaElementType.element.getName()))
		{
			MoxlElement nameElement = patternDefinitionElement.getChildElement(0);
			MoxlElement patternElement = patternDefinitionElement.getChildElement(1);
			MoxlAttribute nsAttr = nameElement.getAttributeMap().get("ns");
			String nsString = nsAttr.getValue();
			XmlNamespace ns = new XmlNamespace(nsString);
			if (nsString.equals(""))
			{
				// TODO: We will interpret this to mean the default namespace. However, there is some more work to do (I think in the simplification process) to
				// ensure that these ns attributes are set correctly.
				ns = DefaultXmlNamespace.getInstance();
			}
			QualifiedName name = new DefaultQualifiedName(ns, nameElement.getContent());
			NameClass nameClass = new Name(name);
			return new ElementPattern(nameClass, createPattern(patternElement));
		}
		else if (patternName.equals(RelaxNgSchemaElementType.choice.getName()))
		{
			MoxlElement blue = patternDefinitionElement.getChildElement(0);
			MoxlElement red = patternDefinitionElement.getChildElement(1);
			return new ChoicePattern(createPattern(blue), createPattern(red));
		}
		else if (patternName.equals(RelaxNgSchemaElementType.empty.getName()))
		{
			return new EmptyPattern();
		}
		else
		{
			throw new UnsupportedOperationException("Pattern not supported: " + patternName.getLocalPart());
		}
	}
}
